package persistent;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MigratorServer extends Thread {
	
	private static final int PORT_RECOVERY = 5240;
	
	private ServerSocket serverSocket;
	
	protected boolean active = true;
	
	private File logFile;
	
	private SimpleDateFormat sdf;
	
	public MigratorServer() throws IOException{
		
		serverSocket = new ServerSocket(PORT_RECOVERY);
		
		logFile = new File("LogVehiculos_Principal.log");
		
		sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS");
	}
	
	public void run(){
		
		while(active){
			
			try {
				Socket socket = serverSocket.accept();
				ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
				String frame = (String)ois.readObject();
				
				BufferedWriter bw = new BufferedWriter(new FileWriter(logFile, true));
				
				bw.write("\n" + frame);
				
				bw.close();
				
				System.out.println("Trama almacenada! " + sdf.format(new Date()));
				System.out.println(frame);
				
				ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
				oos.writeObject(true);
				
				socket.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			
		}
		
		try {
			serverSocket.close();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
	}

}
